package com.myccb.app.view.fragment;

import android.widget.LinearLayout;
import android.widget.TextView;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.myccb.app.AppStatus;
import com.myccb.app.view.index.LoanActivity;
import com.myccb.app.view.activity.LoginActivity;
import com.myccb.app.view.index.LongPayActivity;
import com.myccb.app.R;
import com.myccb.app.base.RequestManager;
import com.myccb.app.view.activity.TransRecordActivity;
import com.myccb.app.view.activity.TransferActivity;
import com.myccb.app.base.BaseFragment;
import com.myccb.app.util.BCNumUtil;

import com.myccb.app.util.DateTimeUtil;
import com.myccb.app.util.NumberUtil;
import com.myccb.app.widget.CommonDialog;
import com.myccb.app.widget.EditTextClearable;
import com.myccb.app.widget.LoadingCountdownDialog;
import com.myccb.app.widget.SubTitleBar;

import com.myccb.app.util.TimeUtil;

import com.myccb.app.widget.rollpageview.ColorPointHintView;
import com.myccb.app.widget.rollpageview.LoopPagerAdapter;
import com.myccb.app.widget.rollpageview.RollPagerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by hyt on 2017/11/24.
 */

public class IndexFragment extends BaseFragment {

    private static IndexFragment instance;

    private TextView sumMoney;
    private TextView refreshTime;
    private TextView BCNumView;

    private TextView welcomeView;
    private TextView queryBalanceBtn;


    private LinearLayout headerLayoutNologin;
    private RelativeLayout headerLayoutLogin;

    private String balance;
    private boolean hideBalance = true;
    private String BCNum;

    private ImageView refreshBtn;
    private LoadingCountdownDialog loadingCountdownDialog;
    private CommonDialog errorMsgDialog;

    private Drawable currencyDrawable;

    private TextView phone_pay;
    private ImageView phone_people;
    private String username, usernumber;


    public static IndexFragment getInstance() {
        if (instance == null)
            instance = new IndexFragment();
        return instance;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_index, null);
        initView(view);
        initData();
        setTransferCard(view);
        setChargePhoneBillCard(view);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }


    private void initView(View view) {


        (view.findViewById(R.id.icon_long_pay)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), LongPayActivity.class);
                startActivity(intent);
            }
        });

        (view.findViewById(R.id.index_loan_btn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoanActivity.class);
                startActivity(intent);
            }
        });

        phone_pay = view.findViewById(R.id.phone_pay);
        phone_people = view.findViewById(R.id.phone_people);
        phone_people.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{
                            Manifest.permission.READ_CONTACTS
                    }, 1);
                } else {
                    startActivityForResult(new Intent(
                            Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 0);
                }
            }

        });

        RollPagerView indexAdv = view.findViewById(R.id.index_mainpage_ads);
        loadingCountdownDialog = new LoadingCountdownDialog(getContext());
        refreshBtn = view.findViewById(R.id.refresh_info);
        refreshBtn.setPivotX(refreshBtn.getWidth() / 2);
        refreshBtn.setPivotY(refreshBtn.getHeight() / 2);

        headerLayoutNologin = view.findViewById(R.id.index_header_nologin);
        headerLayoutLogin = view.findViewById(R.id.index_header_login);

        welcomeView = view.findViewById(R.id.index_welcome_view);
        queryBalanceBtn = view.findViewById(R.id.query_balance_btn);

        queryBalanceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }
        });

        final CheckBox hideBtn = view.findViewById(R.id.checkbox_hide_sum_money);
        sumMoney = view.findViewById(R.id.sum_money);
        refreshTime = view.findViewById(R.id.last_refresh_time);
        BCNumView = view.findViewById(R.id.lab_sum_money);
        BCNumView.setText("总资产");

        refreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshBtnRotate();
                new GetUserInfoTask().execute(2);
                //refreshBtn.setRotation(360);
            }
        });

        hideBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                hideBalance = !isChecked;
                if (isChecked) {
                    sumMoney.setCompoundDrawables(currencyDrawable, null, null, null);
                    sumMoney.setText(balance);
                } else {
                    sumMoney.setCompoundDrawables(null, null, null, null);
                    sumMoney.setText("****");
                }

            }
        });

        indexAdv.setHintView(new ColorPointHintView(getContext(), getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.Grey200)));
        indexAdv.setAdapter(new LoopPagerAdapter(indexAdv) {
            private int[] adImgs = {
                    R.mipmap.index_main_home_adv_1, R.mipmap.index_main_home_adv_2,
                    R.mipmap.index_main_home_adv_3, R.mipmap.index_main_home_adv_4
            };

            @Override
            public View getView(ViewGroup container, int position) {
                ImageView view = new ImageView(container.getContext());
                view.setImageResource(adImgs[position]);
                view.setScaleType(ImageView.ScaleType.CENTER_CROP);
                view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                return view;
            }

            @Override
            public int getRealCount() {
                return adImgs.length;
            }
        });

        errorMsgDialog = new CommonDialog(getContext());


        currencyDrawable = getResources().getDrawable(R.mipmap.currency_white);
        currencyDrawable.setBounds(0, 0, currencyDrawable.getIntrinsicWidth(), currencyDrawable.getIntrinsicHeight());


        (view.findViewById(R.id.index_transfer_btn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), TransferActivity.class);
                getActivity().startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right, android.R.anim.fade_out);
            }
        });

        (view.findViewById(R.id.index_trans_record_btn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), TransRecordActivity.class);
                getActivity().startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right, android.R.anim.fade_out);
            }
        });

        SubTitleBar recentTransfer = view.findViewById(R.id.recent_transfer);
        recentTransfer.setOnRightTextClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), TransRecordActivity.class);
                getActivity().startActivity(intent);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            ContentResolver reContentResolverol = getActivity().getContentResolver();
            Uri contactData = data.getData();
            @SuppressWarnings("deprecation")
            Cursor cursor = getActivity().managedQuery(contactData, null, null, null, null);
            cursor.moveToFirst();
            username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
                    null,
                    null);
            while (phone.moveToNext()) {
                usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                phone_pay.setText(usernumber);
            }

        }
    }

    private void initData() {
        if (AppStatus.isLogin) {
            switchHeaderLayout(1);
            new GetUserInfoTask().execute(0);
        } else if (AppStatus.getInstance().isSaveUserInfo()) {
            switchHeaderLayout(0);
            welcomeView.setText(DateTimeUtil.getCurrentPeriodOfDay() + "好！" + AppStatus.getInstance().getSavedUserName());
            welcomeView.setText(TimeUtil.getCurrentPeriodOfDay() + "好！" + AppStatus.getInstance().getSavedUserName());
            queryBalanceBtn.setText("查询余额");
        } else {
            switchHeaderLayout(0);
            welcomeView.setText(DateTimeUtil.getCurrentPeriodOfDay() + "好！");

            welcomeView.setText(TimeUtil.getCurrentPeriodOfDay() + "好！");

            queryBalanceBtn.setText("马上登陆");
        }
    }

    private void refreshBtnRotate() {
        //SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        //Date curDate =  new Date(System.currentTimeMillis());

        refreshTime.setText(DateTimeUtil.getCurrentDateTime("yyyy/MM/dd HH:mm:ss")/*formatter.format(curDate)*/);
        refreshTime.setText(TimeUtil.getCurrentDateTime("yyyy/MM/dd HH:mm:ss")/*formatter.format(curDate)*/);
        Animation rotateAnimation = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setDuration(1000);
        rotateAnimation.setRepeatCount(0);
        rotateAnimation.setInterpolator(new LinearInterpolator());
        refreshBtn.startAnimation(rotateAnimation);
    }


    private void switchHeaderLayout(int mode) {
        switch (mode) {
            case 0:
                headerLayoutNologin.setVisibility(View.VISIBLE);
                headerLayoutLogin.setVisibility(View.INVISIBLE);
                break;
            case 1:
                headerLayoutNologin.setVisibility(View.INVISIBLE);
                headerLayoutLogin.setVisibility(View.VISIBLE);
                break;
        }

    }

    private class GetUserInfoTask extends AsyncTask<Integer, Void, Integer> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(Integer... integers) {
            HashMap<String, String> postParams = new HashMap<>();
            switch (integers[0]) {
                case 0:
                    postParams.put("item", "all");
                    break;
                case 1:
                    postParams.put("item", "BCNum");
                    break;
                case 2:
                    postParams.put("item", "mainBCBalance");
                    break;
            }
            String result = RequestManager.getInstance(getContext()).requestSyn("getUserInfo.php", RequestManager.TYPE_POST_FORM, postParams);
            Log.d("index", result);
            JSONObject jb = null;
            try {
                jb = new JSONObject(result);
                int status = jb.getInt("status");
                if (status == 0) {
                    int code = jb.getInt("code");
                    return code * 10 + integers[0];
                } else if (status == 1) {
                    jb = jb.getJSONObject("result");

                    if (jb != null) {
                        if (jb.has("mainBCNum"))
                            BCNum = jb.getString("mainBCNum");
                        if (jb.has("balance"))
                            balance = jb.getString("balance");
                    }
                    //result=jb.getString("phoneNum");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return integers[0];
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            if (integer / 10 != 0) {
                showError(integer / 10);
                return;
            }
            switch (integer) {
                case 0:
                    refreshBtnRotate();
                    if (!hideBalance)
                        sumMoney.setText(balance);
                    BCNumView.setText(BCNum.substring(0, 4) + "***" + BCNum.substring(BCNum.length() - 4, BCNum.length()));
                    break;
                case 1:
                    break;
                case 2:
                    //refreshBtnRotate();
                    if (!hideBalance) {
                        sumMoney.setCompoundDrawables(currencyDrawable, null, null, null);
                        sumMoney.setText(balance);
                    }
            }
        }
    }

    private void showErrorMsg(String msg, int code) {
        errorMsgDialog.showMessage(msg, "错误代码:" + code);
    }

    private void showErrorMsg(String msg) {
        errorMsgDialog.showMessage(msg);
    }

    private void showError(int code) {

    }

    private EditTextClearable transferName, transferNum, transferAmount;
    private TextView transferBtn;

    private void setTransferCard(View view) {
        transferName = view.findViewById(R.id.transfer_to_name);
        transferNum = view.findViewById(R.id.transfer_to_num);
        transferAmount = view.findViewById(R.id.transfer_amount);
        transferBtn = view.findViewById(R.id.transfer_btn);
        final String[] values = new String[6];
        transferBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (transferName.getText() == null || transferName.getText().toString().length() < 1) {
                    showErrorMsg("请输入收款人姓名！");
                    return;
                }
                if (transferNum.getText().toString().length() < 11) {
                    showErrorMsg("请输入手机号或银行卡号！");
                }
                if (transferAmount.getText() == null || transferAmount.getText().toString().length() < 1) {
                    showErrorMsg("请输入转账金额！");
                    return;
                }
                String num = transferNum.getText().toString();
                boolean isPhoneNum = false;
                if (num.length() < 11) {
                    showErrorMsg("手机号或银行卡号输入有误！");
                    return;
                }

                if (num.length() < 16) {
                    if (!NumberUtil.isPhoneNum(num)) {
                        showErrorMsg("手机号输入有误！");
                        return;
                    } else
                        isPhoneNum = true;
                }
                if (isPhoneNum) {
                    values[0] = "1";
                    values[1] = "1";
                } else if (BCNumUtil.getNameOfBank(num).equals("")) {
                    showErrorMsg("银行卡号输入有误！");
                    return;
                } else {
                    values[0] = "2";
                    if (BCNumUtil.getNameOfBank(num).contains("建设银行")) {
                        values[1] = "1";
                    } else
                        values[1] = "0";
                }
                values[2] = num;
                values[3] = transferName.getText().toString();
                values[4] = transferAmount.getText().toString();
                values[5] = "转账";
                new TransferTask().execute(values);
            }
        });
    }


    private void setChargePhoneBillCard(View view){
        (view.findViewById(R.id.charge_phone_bill_50)).setOnClickListener(new ChargePhoneBillBtnListener());
        (view.findViewById(R.id.charge_phone_bill_100)).setOnClickListener(new ChargePhoneBillBtnListener());
        (view.findViewById(R.id.charge_phone_bill_300)).setOnClickListener(new ChargePhoneBillBtnListener());
        (view.findViewById(R.id.charge_phone_bill_500)).setOnClickListener(new ChargePhoneBillBtnListener());

    }

    class ChargePhoneBillBtnListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {

            if (!AppStatus.isLogin){
                showErrorMsg("请登录后再试！");
                return;
            }
            String phoneNum=phone_pay.getText().toString();
            if (NumberUtil.isPhoneNum(phoneNum.trim())){

                phoneNum=phoneNum.trim();

                TextView textView=(TextView)v;

                String bill=textView.getText().toString().replace("￥","");


                new AsyncTask<String,Void,Integer>(){

                    private boolean chargeSuccess=false;

                    @Override
                    protected void onPreExecute() {
                        loadingCountdownDialog.show(30);
                    }

                    @Override
                    protected Integer doInBackground(String... values) {
                        HashMap<String, String> postParams = new HashMap<>();
                        postParams.put("phoneNum", values[0]);
                        //postParams.put("vcode",vcode);
                        postParams.put("amount", values[1]);
                        String result = RequestManager.getInstance(getContext()).requestSyn("chargePhoneBill.php", RequestManager.TYPE_POST_FORM, postParams);

                        Log.d("login", result);

                        int code=0;

                        JSONObject jb = null;
                        try {
                            jb = new JSONObject(result);
                            int status = jb.getInt("status");
                            if (status == 0) {
                                //transferSuccess = false;
                                chargeSuccess=false;
                                code = jb.getInt("code");
                            } else if (status == 1) {
                               // transferSuccess = true;
                                chargeSuccess=true;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return code;
                    }

                    @Override
                    protected void onPostExecute(Integer integer) {
                        loadingCountdownDialog.dismiss();
                        if (chargeSuccess){
                            Toast.makeText(getContext(),"充值成功！",Toast.LENGTH_LONG).show();
                        }
                        else{
                            switch (integer){
                                case -1:
                                    showErrorMsg("充值失败:请先登录",integer);

                                case 4:
                                    showErrorMsg("充值失败:余额不足",integer);
                                    break;
                                default:
                                    showErrorMsg("充值失败",integer);
                            }
                        }
                    }
                }.execute(phoneNum,bill);
            }
            else
                showErrorMsg("请输入正确的手机号！");
        }
    }


    class TransferTask extends AsyncTask<String, String, Integer> {
        private boolean transferSuccess;

        @Override
        protected void onPreExecute() {
            loadingCountdownDialog.show(30);
        }

        @Override
        protected Integer doInBackground(String... values) {
            int code = 0;
            HashMap<String, String> postParams = new HashMap<>();
            postParams.put("type", values[0]);
            //postParams.put("vcode",vcode);
            postParams.put("isIntra", values[1]);
            postParams.put("toNum", values[2]);
            postParams.put("toName", values[3]);
            postParams.put("amount", values[4]);
            postParams.put("summary", values[5]);

            String result = RequestManager.getInstance(getContext()).requestSyn("transfer.php", RequestManager.TYPE_POST_FORM, postParams);

            Log.d("login", result);

            JSONObject jb = null;
            try {
                jb = new JSONObject(result);
                int status = jb.getInt("status");
                if (status == 0) {
                    transferSuccess = false;
                    code = jb.getInt("code");
                } else if (status == 1) {
                    transferSuccess = true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return code;
        }

        @Override
        protected void onPostExecute(Integer code) {
            loadingCountdownDialog.dismiss();
            if (transferSuccess) {
                Toast.makeText(getContext(), "转账成功！", Toast.LENGTH_LONG).show();
                refreshBtnRotate();
                new GetUserInfoTask().execute(2);
                /*SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Date curDate = new Date(System.currentTimeMillis());
                AppStatus.lastLoginTime = formatter.format(curDate);*/
                //finish();
            } else {
                switch (code) {
                    case 5:
                        showErrorMsg("您不能为自己转账！", code);
                        break;
                    case 9:
                        showErrorMsg("转账失败:账户余额不足！", code);
                }
                //showLoginError(code);
            }
        }
    }
}